package com.recource.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.recource.annonation.Login;
import com.recource.dao.*;
import com.recource.domain.*;
import com.recource.ro.PageRO;
import com.recource.ro.PushVipProjectRO;
import com.recource.util.ReqContextUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author xjhStart
 * @create 2023-04-30 下午1:47
 */
@Controller
@RequestMapping("/coach")
@Transactional(rollbackFor = Exception.class)
@Login
public class CoachController {


    @Autowired
    private CoachMapper coachMapper;

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserDao userDao;


    //查看指定id的教练业绩
    @RequestMapping("/performance")
    public ModelAndView selectPerformance(PageRO<Order> ro){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/coach/performance/list");

        if(StringUtils.isNotEmpty(ro.getSearch())){
            throw new RuntimeException("参数不能为空");
        }

        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getCoach_id,ro.getSearch());
        PageRO<Order> page = orderMapper.selectPage(ro, wrapper);

        modelAndView.addObject("order",page);
        return modelAndView;

    }

    //推送套餐给学员
    @RequestMapping("/push")
    public ModelAndView push(PushVipProjectRO ro){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/coach/push/success");


        LambdaQueryWrapper<Project> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Project::getId,ro.getProjectId());
        Project project = projectMapper.selectOne(wrapper);

        String topic = ro.getCoachId()+ro.getVipId();
        ReqContextUtils.publishMessage(topic,project);

        return modelAndView;
    }


    //个人信息编辑
    @RequestMapping("/edit")
    public ModelAndView edit(String id){
        ModelAndView modelAndView = new ModelAndView();

        Coach coach = coachMapper.selectById(id);

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId,coach.getUserId());
        User user = userDao.selectOne(wrapper);


        //如果用户不存在就报错
        if(coach == null){
            throw new RuntimeException("用户不存在");
        }
        //跳转页面
        modelAndView.setViewName("/coach/edit");
        //将用户信息注入视图层
        modelAndView.addObject("coach", coach);
        modelAndView.addObject("user",user);
        return modelAndView;
    }


}
